const app = getApp();

const RongIMLib = app.globalData.RongIMLib;

const RongIMEmoji = app.globalData.RongIMEmoji;

const utils = require("../../utils/utils.js")


const src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550811235181&di=ed6d32826fdda6d72c991071e008cfc8&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01fd3e571dda8032f875a3996cb52f.jpg%402o.jpg";

var params = {
    appKey: "x18ywvqfxc6nc",
    self : null
};

Page({
    data: {
        auction_start_time:"",       // 活动开始时间
		auction_status: 0,		     // 活动状态 -1 已结束 1 进行中 0 未开始

        user_data:'',                // 用户微信端数据

        goodsDetail: '',             // 活动商品
        auction_id: "",            	 // 活动id
		room_id:"",	                 // 聊天室id

        goods_status: false,         // 活动状态 -  用户端查看
        auction_role: "",            // 活动 角色     0 : 普通用户  1 : 管理员  2 : 主持人 

        goods_id:"",                 // 当前活动商品id
        
        chart_topper:"",             // 当前最高价用户
		purchaser:"",				 // 当前商品 拍中信息
        price:0,                     // 加价金额

        price_status:1,              // 当前竞拍方式

        entrust_price:"",            // 委托出价数据

        message: '',                 // 发送的消息
        toView:'',                   // 当前消息id
        last_sendTime:'',            // 最后一条发送的消息时间
        last_content:'',             // 最后一条发送的消息内容
        messageList: [],             // 消息记录

        emojiList:[],                // 表情数据

        customText:'',               // 自定义加价金额
        range:10,                    // 加价范围

        auctionText:1,               // 按钮状态   1 ： 开始拍卖  2 ： 开始倒计时  3 进入倒计时

        countDownFun:null,           // 倒计时方法
		countDown:false,			 // 开始倒计时
		countDownTime:10,			 // 倒计时时间
    
        scrollHeight:0,
        keyboardHeight:0,            // 键盘高度

		verbalTrickList:"",			 //话术数据列表
		verbalTrickShow:false,	     // 显示话术

        is_last:false,               // 是否是最后一件拍品
        last_goods:false,            // 最后一件商品是否已拍卖

        aution_is_end:false,         // 活动是否结束

        this_id: "",                 // 自己的用户id
        user_id: "",                 // 当前聊天对方用户id

        isAllowScroll: true,         // 是否加载中
        hasMsg: true,                // 是否有历史记录

        show_accredit:false,         // 显示授权
        is_phone_auth:false,         // 是否授权平台
        auction_phone_auth:false,    // 是否授权商家

        auction_margin:0,            // 活动保证金
        now_margin:0,                // 当前保证金
        auction_shutup: 0,           // 活动是否禁言

        chatRoom:false,              // 加入聊天室状态
    },
    // 开始活动提示
    showStartDialog(){
        this.dialog_start.showDialog();
    },
	// 开始活动
	startActive() {
		var self = this;
		var url = "/chatroom/start_auction";
		var auction_id = this.data.auction_id;

		wx.getStorage({
			key: 'user',
			success: function (res) {
				wx.request({
					url: app.url.requestUrl + url,
					method: 'POST',
					data: {
						openid: res.data.openid,
						token: res.data.token,
                        type:1,
						auction_id
					},
					success: function (res) {
						var datas = res.data;
						if (datas.code == 1) {
							self.getStatus();
							self.getNowGoodsData();
                            sendCustomMessage("auctionStart")
						} else {
							wx.showToast({
								image: '../../img/warning.png',
								title: datas.msg,
							})
						}
					}
				})
			}
		})
	},
	// 获取 活动开始状态、人物状态
	getStatus() {
		var self = this;
		var auction_id = this.data.auction_id;
		var auction_role = '';
		var url = "/chatroom/is_host";
		var chart_topper = this.data.chart_topper;
		var auctionText = this.data.auctionText;
		wx.getStorage({
			key: 'user',
			success: function (res) {
				wx.request({
					url: app.url.requestUrl + url,
					method: 'POST',
					data: {
						openid: res.data.openid,
						token: res.data.token,
						auction_id: auction_id,
					},
					success: function (res) {
						var datas = res.data;

						if (datas.code == -1) {
							self.loginOverdue();
							return false;
						}

						if (datas.code == 1) {

							self.setData({
								auction_status: datas.data.status,
								auction_role: datas.data.is_manage
							})
							if (datas.data.status == 0){ 	// 活动未开始
								self.setData({
									goods_status: false,
									auctionText: 0
								})
							}
							if (datas.data.status == -1) {	 // 活动结束
								self.setData({
									aution_is_end: true,
									goods_status: false,
									auctionText: 0
								})
							}
							self.getNowGoodsData();
							self.getUserInfo();
							
                            if (!params.status) {
                                self.chatRoomRongIMLibInit();
                            }
						} else {
							wx.showToast({
								image: '../../img/warning.png',
								title: datas.msg,
							})
						}
					}
				})
			}
		})
	},
    // 获取当前正在拍卖的商品数据、当前商品拍卖状态、当前出价最高者、 
    getNowGoodsData(){
        var self = this;
        var auction_id = this.data.auction_id;
        var url = "/chatroom/current_auction_goods";

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.setData({
                                is_phone_auth: datas.data.is_phone_auth,
                                auction_phone_auth: datas.data.auction_phone_auth,
                                goodsDetail: datas.data,
                                auction_margin: datas.data.margin,
                                now_margin: datas.data.cash_deposit,
                                auction_shutup: datas.data.ban_status,
                                auction_start_time: datas.data.start_time
                            })
                            wx.setNavigationBarTitle({ title: datas.data.act_name || '开始拍卖' })
                            if (datas.data.auction_status == 1){
								self.setData({ auctionText: 2, goods_status: true })
                            } else {
								self.setData({ auctionText: 1, goods_status: false })
                            }
                            
                            var chart_topper = "";

                            if (datas.data.user_id != 0){
                                chart_topper = {
                                    price: datas.data.price,
                                    nickname: datas.data.nicke_name || 'xxx',
                                    photo: datas.data.header_img || src,
                                }
                            }
                            
                            self.setData({
                                range: datas.data.range,
                                price_status: datas.data.price_status,
                                is_last: datas.data.is_last,
                                chart_topper: chart_topper
                            })
                        } else {
                            wx.showToast({
                                image: '../../img/warning.png',
								title: datas.msg ? datas.msg : "商品获取失败",
                            })
                        }
                        if (params.status){
                            wx.hideLoading()
                        }
                    }
                })
            }
         })
    },
    // 获取下一件商品数据
    getNextGoodsData(type) {
        var self = this;
        var auction_id = this.data.auction_id;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + "/chatroom/get_auction_goods",
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.setData({
                                chart_topper:"",
                                purchaser:"",
                                goodsDetail: datas.data,
                                range: datas.data.range || 0,
                                price_status: datas.data.price_status || 1
                            })
                            
                            sendCustomMessage("start");
                           

                            if (datas.data.is_last == 1){
                                wx.showToast({ title: '最后一件商品了' })
                                self.setData({ is_last : true })
                            }
                        } else {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: "商品获取失败",
                            })
                        }
                    }
                })
            }
        })
    },
    // 输入消息
    inputMessage(e) {
        this.setData({ message: e.detail.value })
    },
	// 输入框获取焦点
    focusEvent(e){
		
	},
    // 输入框失去焦点
    blurEvent(e){
        this.setData({
            faceEmojiShow:false,
            verbalTrickShow: false,
        })
    }, 
	// 获取话术列表
	getVerbalTrick(){
		var self = this;
		var url = '/index/verblist';

		wx.getStorage({
			key: 'user',
			success: function (res) {
				wx.request({
					url: app.url.requestUrl + url,
					method: 'POST',
					data: {
						openid: res.data.openid,
						token: res.data.token,
					},
					success: function (res) {
						if (res.data.code == 1) {
							self.setData({
								verbalTrickList: res.data.data,
							})
						}
					}
				})
			},
		})
	},
    // 显示表情列表
    showFaceEmoji(){
        var auction_shutup = this.data.auction_shutup;
        if (auction_shutup) {
            return false;
        }
        this.setData({
            verbalTrickShow:false,
            faceEmojiShow:true
        })
    },
    // 选择表情
    selectFaceEmoj(e){
        var self = this;
        var emoji = e.target.dataset.emoji;
        var message = this.data.message;
        this.setData({
            verbalTrickShow: false,
            message: message + emoji
        })
    },
	// 显示话术列表
	showVerbalTrick(){
        this.getVerbalTrick();
		this.setData({
            faceEmojiShow:false,
			verbalTrickShow: true
		})
	},
	// 选择话术
	selectVerbalTrick(e){
		var self = this;
		var content = e.target.dataset.content;

		this.setData({
			verbalTrickShow:false,
			message: content,
		})
	},
    // 发送消息
    sendMessage(e) {
        var message = this.data.message;
        var auction_id = this.data.auction_id;
        var user_id = this.data.user_id;
        this.setData({
            faceEmojiShow: false,
            verbalTrickShow: false,
        })
		if (!message){
			wx.showToast({
				image:'../../img/warning.png',
				title: '请输入内容',
			})
		}else{
            if (auction_id){
                sendTextMessage( message);
            }
            if(user_id){
                sendMessagePrivate(this, message);
            }
		}
        
    },
    // 加价
    addPirce(e){
        var price = e.target.dataset.price;
        this.goodsPriceLift(price);
    },
    customPrice(e){ 
        //显示 加价框
        this.dialog.showDialog();
    },
    // 加价输入
    customInput(e){
        var value = e.detail.value;
        this.setData({customText:value})
    },
    // 商品加价
    goodsPriceLift(num) {
        var self = this;
        var auction_id = this.data.auction_id;
        var goods_id = this.data.goodsDetail.id;
        var price = num;
        var url = "/chatroom/raiseup";
        var is_phone_auth = this.data.is_phone_auth;
        var auction_phone_auth = this.data.auction_phone_auth;

        var now_margin = this.data.now_margin;
        var auction_margin = this.data.auction_margin;
    
        if (now_margin < auction_margin){ // 保证金不足
            this.dialog_margin.showDialog();
            return false;
        }

        if (!auction_phone_auth){	// 未授权手机号
			this.setData({ show_accredit:true })
            return false;
        }

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id,
                        goods_id, 
                        price
                    },
                    success: function (res) {
                        var datas = res.data;

                        if (datas.code == 1) {
                            wx.showToast({title: datas.msg,})
                            sendTextMessage(datas.data.price,"price");
                            if (datas.data.entrust.entrust_price != 0){
                                self.setData({
                                    entrust_price: datas.data.entrust
                                })
                                setTimeout(function(){
                                    sendTextMessage(datas.data.entrust.entrust_price, "system_price");
                                },500)
                            }
                            self.setData({ range : datas.data.range })
                            if (datas.data.type == 1){
                                // 成交订单
                                self.getLastrRaise();
                            }
                        }else{
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 一口价
    itemPrice(){
        var self = this;
        var url = "/chatroom/one_price";
        var auction_id = this.data.auction_id;
        var goods_id = this.data.goodsDetail.id;
        var now_margin = this.data.now_margin;
        var auction_margin = this.data.auction_margin;
        var auction_phone_auth = this.data.auction_phone_auth;

        if (now_margin < auction_margin) { // 保证金不足
            this.dialog_margin.showDialog();
            return false;
        }

        if (!auction_phone_auth) {	// 未授权手机号
            this.setData({ show_accredit: true })
            return false;
        }

        wx.showLoading({title: '抢购中...'})

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id,
                        goods_id,
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.getLastrRaise();
                        } else {
                            wx.showToast({
                                image:"../../img/warning.png",
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
	// 禁言 
	shutUp(){
		this.dialog_shut_up.showDialog();
	},
	// 开始当前商品竞拍
	startAuction(){
		this.dialog_start_auction.showDialog();
	},
    // 开始倒计时
    startCountDown(){
        var self = this;
        var chart_topper = this.data.chart_topper;
        var time = this.data.countDownTime;
        wx.showLoading({title: '计算中...'})
    
        this.setData({
            countDown:true,
            auctionText : 3
        })
       
        var countDownFun = setInterval(() => {
            wx.hideLoading();
            if (self.data.countDown && time > 0){
                sendCountDown(time);
                self.setData({
                    countDownTime: time
                })
            }else{
                // 暂停
                if (!self.data.countDown){
                    self.setData({
                        countDownTime: 10,
                        auctionText: 2
                    })
                    clearInterval(countDownFun)
                    countDownFun = null;
                }else{ // 倒计时结束
                    self.setData({
                        auctionText:4,
                        countDownTime: 10,
                    })
                    clearInterval(countDownFun)
                    countDownFun = null;
                    console.log("倒计时结束")
                }
                // 倒计时结束  请求*********************************************************************************
            }
            time --;
        },3000)
        this.setData({countDownFun})
    },
    // 成交按钮
    closingTheDeal(){
        this.getLastrRaise();
    },
    // 拍卖结束获取成交价
	getLastrRaise(){
		var self = this;
		var url = "/chatroom/getlastraise";
		var auction_id = this.data.auction_id;
        var goods_id = this.data.goodsDetail.id;

		wx.getStorage({
			key: 'user',
			success: function (res) {
				wx.request({
					url: app.url.requestUrl + url,
					method: 'POST',
					data: {
						openid: res.data.openid,
						token: res.data.token,
						auction_id,
						goods_id,
					},
					success: function (res) {
						var datas = res.data;
						if (datas.code == 1) {
                            self.setData({
                                purchaser: datas.data
                            })
                            sendCustomMessage("end");
						}
                        if(datas.code == 0){
                            self.setData({
                                auctionText: 1
                            })
							wx.showToast({
								image: '../../img/warning.png',
								title: datas.msg,
							})
                            sendCustomMessage("drain");
						}
					}
				})
			}
		})
	},
    onLoad: function (options) {
        wx.showLoading({
            title: '加载中',
            mask: true
        })

        var self = this;
        params.room_id = options.id ? "chatRoomId" + options.id : "chatRoomId146";    // 聊天室id
        params.self = this;

        this.dialog = this.selectComponent("#dialog");
        this.dialog_start = this.selectComponent("#dialog-start");
        this.dialog_repeal = this.selectComponent("#dialog-repeal");
        this.dialog_phone = this.selectComponent("#dialog-phone");
        this.dialog_shut_up = this.selectComponent("#dialog-shut-up");
        this.dialog_margin = this.selectComponent("#dialog-margin");
        this.dialog_start_auction = this.selectComponent("#dialog-start-auction");

        this.login = this.selectComponent("#login");
        this.phone = this.selectComponent("#phone");

        this.setData({
            auction_id: options.id || "146",
			auction_name: options.name || '',
        })
		this.chatRoomLoginLoad()
    },
	onShareAppMessage(options){
		var auction_id = this.data.auction_id;
        var auction_name = this.data.auction_name || this.data.goodsDetaill.act_name;
		if (options.form == "button"){
			console.log("来自按钮")
		}
		return {
			title: '拍卖活动：' + auction_name,
			path: `/pages/my-lots-chat-room/my-lots-chat-room?id=${auction_id}&name=${auction_name}`
		}
	},
	// 聊天室 - 登录后加载数据
	chatRoomLoginLoad(){
		var self = this;
		wx.getStorage({
			key: 'user',
			success: function (res) {
				console.log("已登录")
				self.getStatus();
			},
			fail() {
				console.log("未登录")
				wx.login({
					success: res => {
						wx.request({
							url: app.url.requestUrl + '/login/login',
							method: 'POST',
							data: {
								code: res.code
							},
							success: function (data) {
                                var datas = data.data;
								if (data.data.code == 1) {
									wx.setStorage({
										key: 'user',
										data: data.data.data
									})
                                    self.getStatus();
								}
							}
						})
					}
				})
			}
		})
	},
	// 显示页面
	onShow() {
        if (params.status){
            joinChatRoom();
        }
	},
    // 卸载页面
    onUnload(){
        var self = this;
        console.log("卸载页面吧" + params.room_id)
        var chatRoomId = params.room_id; // 聊天室 Id。
        if (params.room_id){
            RongIMLib.RongIMClient.getInstance().quitChatRoom(chatRoomId, {
                onSuccess: function () {
                    console.log("退出聊天室成功");
					params.status = false;
                    params.self.setData({
                        messageList: [],
                    })
                },
                onError: function (error) {
                    console.log("退出聊天室失败")
                }
            });
        }
    },
    // 切换 显示 隐藏 授权弹窗
    toggleAccredit(){
        var show_accredit = this.data.show_accredit;
        this.setData({ show_accredit: !show_accredit })
    },
    // 获取授权弹窗
    // accreditPhone(){
    //     this.getUserPhone();
    // },
    // 获取用户手机号
    getUserPhone(){
        var is_phone_auth = this.data.is_phone_auth;
        var auction_phone_auth = this.data.auction_phone_auth;

        if (!is_phone_auth){
            this.phone.showModalBox();
        }else{
            this.accredit();
        }
    },
    // 登录授权
    getUserInfo(){
        var self = this;
        //获取用户信息
        wx.getSetting({
            success: res => {
                if (!res.authSetting['scope.userInfo']) {
                    this.login.showModalBox()
                }else{
                    //已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getStorage({
                        key: 'user_info',
                        success(res){
                            self.setData({
                                user_data : res.data
                            })
                        },
                        fail(){
                            wx.getUserInfo({
                                success(res) {
                                    self.uploadUserInfo(res.userInfo);
                                }
                            })
                        }
                    })
                }
            }
        })
    },
    // 授权手机号
    __accreditPhoneEvent(e){
        if (e.detail.errMsg == 'getPhoneNumber:user deny') {
            wx.showToast({
                image:'../../img/warning.png',
                title: '未同意授权',
            })
        } else {
            this.judup_session_key(e.detail.phone);
            this.phone.hideModalBox();
        }
    },
    // 解码手机号
    decodePhone(data){
        var self = this;
        var url = "/chatroom/authPhone";

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        session_key: res.data.session_key,
                        encryptedData: data.encryptedData,
                        iv:data.iv
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.accredit();
                        }else{
                            wx.showToast({
                                image:"../../img/warning.png",
                                title: datas.msg.toString(),
                            })
                        }
                    }
                })
            }
        })
    },
    // 判断 session_key 是否过期
    judup_session_key(phone){
        var self = this;
        wx.checkSession({
            success(){
                self.decodePhone(phone)
            },
            fail(){
                wx.login({
                    success: res => {
                        wx.request({
                            url: app.url.requestUrl + '/login/login',
                            method: 'POST',
                            data: {
                                code: res.code
                            },
                            success: function (data) {
                                var datas = data.data;
                                if (data.data.code == 1) {
                                    wx.setStorage({
                                        key: 'user',
                                        data: data.data.data
                                    })
                                }
                                self.decodePhone(phone)
                            }
                        })
                    }
                })
            }
        })
    },
    accredit(){
        var self = this;
        var url = "/chatroom/auth_auction_phone";
        var auction_id = this.data.auction_id
        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            wx.showToast({
                                title: '授权手机号成功',
                            })
                            self.setData({
                                is_phone_auth:1,
                                auction_phone_auth:1,
                                show_accredit: false
                            })
                        } else {
                            wx.showToast({
                                image: "../../img/warning.png",
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 确认授权登录
    __accreditEvent(e) {
        this.uploadUserInfo(e.detail.user_info)
        this.login.hideModalBox()
    },
    // 登录成功上传头像及用户信息
    uploadUserInfo(info){
        var self = this;
        var url = "/user/save_user_info";
        var name = info.nickName;
        var header_img = info.avatarUrl

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        name,
                        header_img
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1){
                            wx.setStorage({
                                key: 'user_info',
                                data: info,
                            })
                            self.setData({
                                user_data: info
                            })
                        }
                    }
                })
            }
        })
    },
    // 初始化融云
    chatRoomRongIMLibInit() {
        joinChatRoom();
    },

    // 开始活动 - 确认按钮
    __startActivityEvent(){
        this.startActive();
        this.dialog_start.hideDialog();
    },
    // 开始活动 - 取消按钮
    __startActivityCancelEvent(){
        this.dialog_start.hideDialog();
    },

    // 撤销此拍 - 确认按钮
    __confirmRepealYesEvent(){
        console.log("撤销成功")
        this.repealAuction();
        this.dialog_repeal.hideDialog();
    },
    // 撤销此拍 - 取消按钮
    __confirmRepealNoEvent() {
        console.log("取消撤销")
        this.dialog_repeal.hideDialog();
    },
    // 加价 - 弹窗点击确认 按钮触发函数
    __confirmCustomEvent(e) {
        console.log("加价成功")
        var range = this.data.range;
        var customText = this.data.customText;

        if (customText < range){
            wx.showToast({
                image:"../../img/warning.png",
                title: '金额需大于' + range,
            })
            return false;
        }
        this.setData({ price: customText})
        this.goodsPriceLift(customText);
        this.dialog.hideDialog();
    },
    // 加价 - 取消按钮
    __confirmCustomCancelEvent() {
        this.dialog.hideDialog();
    },
    // 禁言 - 确认按钮
    __shutUpEvent() {
        var self = this;
        var url = "/chatroom/banned";
        var auction_id = this.data.auction_id;
        var auction_shutup = this.data.auction_shutup;
        this.dialog_shut_up.hideDialog();

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id,
                        type: +!auction_shutup,
                    },
                    success: function (res) {
                        if (res.data.code == 1) {
                            self.setData({
                                auction_shutup: +!auction_shutup
                            })
                            if (auction_shutup) {        // 如果当前是禁言状态
                                sendNotificationMessage("shutup", 0)
                                console.log("解除禁言")
                            } else {                      // 如果当前不是禁言状态
                                sendNotificationMessage("shutup", 1)
                                console.log("全体禁言")
                            }
                        }
                    }
                })
            },
        })

    },
    // 禁言 - 取消按钮
    __shutUpCancelEvent() {
        this.dialog_shut_up.hideDialog();
    },

	// 开始竞拍 - 确认按钮
	__startAuctionEvent(){
		console.log("开始竞拍")
        this.getNextGoodsData();
		this.dialog_start_auction.hideDialog();
	},
	// 开始竞拍 - 取消按钮
	__startAuctionCancelEvent(){
		this.dialog_start_auction.hideDialog();
	},
    // 保证金不足 - 确认
    __marginEvent(){
        this.dialog_margin.hideDialog();
        wx.navigateTo({
            url: '../my-recharge/my-recharge?type=margin&charge_type=2',
        })
    },
    // 保证金不足 - 取消
    __marginCancelEvent(){
        this.dialog_margin.hideDialog();
    },
    // 改变聊天室状态
    changeGoodsStatus(type){
        var self = this;
        var url = "/chatroom/change_goods_status";
        var goods_id = this.data.goodsDetail.id;
        var auction_id = this.data.auction_id;
        var is_last = this.data.is_last;
        var last_goods = this.data.last_goods;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        goods_id,
                        auction_id,
                        type:type,
                    },
                    success: function (res) {
                        var datas = res.data;
                        if(datas.code == 1 && type == 1){
                            self.setData({range:datas.data.range})

                            if (datas.data.entrust.user_id != 0) {
                                self.setData({ entrust_price: datas.data.entrust });
                                sendTextMessage(datas.data.entrust.entrust_price, "system_price");
                            }

                            if (datas.data.type == 1) {         // 成交订单
                                self.getLastrRaise()
                            }
                        }
                        if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
        if (is_last && ( type == -1 || type == 2 ) ){
            this.endAuction();
        }
    },
    // 创建聊天室
    foundChatRoom() {
        var url = "/chatroom/create_chatroom";
        var auction_id = this.data.activeify_id
        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id: auction_id
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
	// 登录过去状态
	loginOverdue(e) {
		var self = this;
		wx.removeStorage({
			key: 'user',
			success: function(res) {
				self.chatRoomLoginLoad();
			},
		})
	},
    // 显示撤销拍卖弹窗
    showRepealAuction(){
        this.dialog_repeal.showDialog();
    },
    // 撤销拍卖
    repealAuction(){
        var self = this;
        sendCustomMessage("repeal")
    },
    changeRongIMStatus(status){
        wx.setStorage({
            key: 'RongIM_S',
            data: status,
        })
    },
    // 结束当前活动
    endAuction(){
        var self = this;
        var url = "/chatroom/start_auction";
        var auction_id = this.data.auction_id;

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        auction_id: auction_id,
                        type:-1
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1){
                            sendCustomMessage("auctionEnd")
                        }else if (datas.code == 0) {
                            wx.showToast({
                                image: '../../img/warning.png',
                                title: datas.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 下拉获取历史记录
    getHistoryList() {
        var hasMsg = this.data.hasMsg;
        if (hasMsg) {
            this.setData({ isAllowScroll: true })
            getHistoryList(5);
        } else {
            this.setData({ isAllowScroll: false })
        }
    }
})

// 加入聊天室
function joinChatRoom() {
    var chatRoomId = params.room_id;       // 聊天室 Id
    var count = 20;             // 拉取最近聊天最多 50 条

    RongIMLib.RongIMClient.getInstance().joinChatRoom(chatRoomId, count, {
        onSuccess: function (message) {
            app.globalData.writeInContent = writeInContent;
            app.globalData.writeInMaterial = writeInMaterial;
            app.globalData.writeInNotification = writeInNotification;
            app.globalData.writeInAuctionStatus = writeInAuctionStatus;
            // 加入聊天室成功。
            params.status = true;
            console.log('加入聊天室成功xxx。' + chatRoomId);
        },
        onError: function (error) {
            // 加入聊天室失败
            console.log('加入聊天室失败。');
        }
    });

    // 获取表情
    getEmojiList()
}
// 获取 emoji 表情数据
function getEmojiList() {
    var list = RongIMEmoji.list;
    var horizontal = 8;
    var vertical = 3;
    var length = -1;
    var emojiList = [];

    list.map(function (item, index) {
        if (index % (horizontal * vertical) == 0) {
            length++;
            emojiList[length] = [];
        }
        emojiList[length].push(item)
    })
    params.self.setData({
        emojiList: emojiList,
    })
}

// 发送文本消息
function sendTextMessage(text,type) {
    type = type || "text";

    var chatRoomId = params.room_id;

    var extra = {
        nickname: params.self.data.user_data.nickName,
        photo: params.self.data.user_data.avatarUrl,
        data_type: type
    }
    if (type == "system_price"){
        extra.nickname = params.self.data.entrust_price.nick_name;
        extra.photo = params.self.data.entrust_price.header_img;
        extra.entrust_price = text;
    }

    var msg = new RongIMLib.TextMessage({ content: text, extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    
    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();
    
    if (now_time - last_sendTime <= 15000 && text == last_content){
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                         // 消息数据列表
            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            
            if (message.content.extra.data_type != 'system_price'){
                messageList.push({
                    messageType: 'text',
                    content: message.content.content,
                    userInfo: {
                        user_id: message.senderUserId,
                        nickname: message.content.extra.nickname || '恒基权品',
                        photo: message.content.extra.photo || src,
                        data_type: message.content.extra.data_type || 'text',
                        range: message.content.extra.range || 10
                    },
                    messageUId: message.messageUId
                })
            }else{
                messageList.push({
                    messageType: 'text',
                    userInfo: {
                        user_id: message.senderUserId,
                        nickname: message.content.extra.nickname || '恒基权品',
                        photo: message.content.extra.photo || src,
                        data_type: message.content.extra.data_type || 'text',
                        entrust_price: message.content.content || {},
                        range: message.content.extra.range || 10
                    },
                    messageUId: message.messageUId
                })
            }
            
            if (message.content.extra.data_type == 'price' || message.content.extra.data_type == 'system_price') {
                
                params.self.setData({
                    chart_topper: {
                        price: message.content.content,
                        nickname: message.content.extra.nickname || '恒基权品',
                        photo: message.content.extra.photo || src,
                        data_type: message.content.extra.data_type || 'price'
                    }
                })
            } 

            messageList = isRepeat(messageList, "messageUId")

            params.self.setData({
                message: '',
                toView: message.messageUId,
                messageList: messageList,
                last_content: text,
                last_sendTime: now_time
            })
            console.log("发送文本消息成功");
        },
        onError: sendError
    })
}
// 发送倒计时
function sendCountDown(text){
    var chatRoomId = params.room_id;
    var msg = new RongIMLib.TextMessage({ content: text, extra: { data_type: 'countDown'}});
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                // 消息数据列表

            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            messageList.push({
                messageType: 'countDown',
                content: message.content.content,
                messageUId: message.messageUId
            })

            messageList = isRepeat(messageList, "messageUId")

            params.self.setData({
                toView: message.messageUId,
                messageList: messageList,
            })
        },
        onError: sendError
    })
}
// 发送自定义消息 资料 - 开始竞拍 - 结束竞拍
function sendCustomMessage( text ){
    var chatRoomId = params.room_id;

    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();

    if (now_time - last_sendTime <= 15000 && text == last_content) {
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    if (text == "auctionStart" || text == "auctionEnd") {    // 如果是开始活动  // 如果是结束活动
        var extra = {
            data_type: text,
        }
    }

    if (text == "start") {                                    // 如果是开始竞拍
        var extra = {
            data_type: text,
            price_status: params.self.data.price_status,
            data: params.self.data.goodsDetail
        }
    }
    if (text == "end") {                                    // 如果是结束竞拍
        console.log(params.self.data.purchaser)
        var extra = {
            data_type: text,
            title: params.self.data.goodsDetail.title,
            price_status: params.self.data.price_status,
            data: params.self.data.purchaser,
        }
    }
    if (text == "repeal") {                                 // 如果是撤销竞拍
        var extra = {
            data_type: text,
            price_status: params.self.data.price_status,
            data: params.self.data.goodsDetail
        }
    }
    if (text == "drain"){
        var extra = {
            data_type: text,
            price_status: params.self.data.price_status,
            data: params.self.data.goodsDetail
        }
    }

    var msg = new RongIMLib.ProfileNotificationMessage({ content: text, extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;
    
    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                            // 消息数据列表
            
            if (message.content.extra.data_type == "auctionStart") {    // 如果是开始活动
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                })
                params.self.getStatus();
            }

            if (message.content.extra.data_type == "auctionEnd") {      // 如果是结束活动
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                })
                params.self.getStatus();
            }

            if (message.content.extra.data_type == "start") {           // 如果是开始竞拍
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        price_status: message.content.extra.price_status,
                        index: message.content.extra.data.len,
                        title: message.content.extra.data.title,
                        goods_id: message.content.extra.data.goods_id,
                    }
                })
                params.self.setData({
                    goods_status: true,
                    auctionText: 2,
                })
                params.self.changeGoodsStatus(1)
            }

            if (message.content.extra.data_type == "end") {              // 如果是结束竞拍
                
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        price_status: message.content.extra.price_status,
                        index: message.content.extra.data.len,
                        price: message.content.extra.data.price,
                        goods_id: message.content.extra.data.goods_id,
                        title: message.content.extra.title,
                        nickname: message.content.extra.data.name,
                    }
                })
                params.self.setData({
                    goods_status: false,
                    auctionText: 1,
                })
                
                params.self.changeGoodsStatus(2)
                wx.hideLoading();
                
            }

            if (message.content.extra.data_type == "repeal") {          // 如果是撤销竞拍
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        price_status: message.content.extra.price_status,
                        index: message.content.extra.data.len,
                        title: message.content.extra.data.title,
                        goods_id: message.content.extra.data.goods_id,
                    }
                })
                params.self.setData({
                    goods_status: false,
                    auctionText: 1,
                })
                params.self.changeGoodsStatus(-1)
            }

            if (message.content.extra.data_type == "drain"){            // 如果是流拍
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        price_status: message.content.extra.price_status,
                        index: message.content.extra.data.len,
                        title: message.content.extra.data.title,
                        goods_id: message.content.extra.data.goods_id,
                    }
                })
                params.self.setData({
                    goods_status: false,
                    auctionText: 1,
                })
                params.self.changeGoodsStatus(-1)
            }

            messageList = isRepeat(messageList, "messageUId")

            params.self.setData({
                toView: message.messageUId,
                messageList: messageList,
                last_sendTime: now_time,
                last_content:text
            })
        },
        onError: sendError
    })
}
// 发送通知消息
function sendNotificationMessage(type, value) {
    var chatRoomId = params.room_id;

    var last_sendTime = params.self.data.last_sendTime;
    var last_content = params.self.data.last_content;
    var now_time = new Date().getTime();

    if (now_time - last_sendTime <= 15000 && text == last_content) {
        wx.showToast({
            image: "../../img/warning.png",
            title: '请勿重复发送',
        })
        return false;
    }

    var extra = {
        data_type: type,
        value: value
    }

    var msg = new RongIMLib.InformationNotificationMessage({ extra: extra });
    var conversationType = RongIMLib.ConversationType.CHATROOM;

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, chatRoomId, msg, {
        onSuccess: function (message) {
            var messageList = params.self.data.messageList;                            // 消息数据列表

            if (message.content.extra.data_type == "shutup") {          // 如果是禁言通知
                messageList.push({
                    messageType: message.content.extra.data_type,
                    messageUId: message.messageUId,
                    content: {
                        value: message.content.extra.value
                    }
                })
            }

            messageList = isRepeat(messageList, "messageUId")

            params.self.setData({
                toView: message.messageUId,
                messageList: messageList,
                last_sendTime: now_time,
                last_content: value
            })
        },
        onError: sendError
    })
}



// 写入文本消息
var writeInContent = function (num, message) {
    var messageList = params.self.data.messageList;

    // message.content.content => 消息内容
    if (message.content.extra){
        if (message.content.extra.data_type == 'price' && params.self.data.countDown){
            params.self.setData({
                goods_status: true,
                countDown: false,
            })
        }

        if (message.content.extra.data_type == 'system_price'){			// 委托出价
            messageList.push({
                messageType: 'text',
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra.nickname || '恒基权品',
                    photo: message.content.extra.photo || src,
                    data_type: message.content.extra.data_type || 'text',
                    entrust_price: message.content.content || {},
                    range: message.content.extra.range || 10
                },
                messageUId: message.messageUId
            })
        } else if (message.content.extra.data_type == 'price' || message.content.extra.data_type == 'text'){
			// 文本消息 || 加价消息
            messageList.push({
                messageType: 'text',
                content: message.content.content,
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra.nickname || '恒基权品',
                    photo: message.content.extra.photo || src,
                    data_type: message.content.extra.data_type || 'text',
                    range: message.content.extra.range || 10,
                    sendTime: utils.getTime(message.sentTime),
                },
                type: 1,
                messageUId: message.messageUId
            })
            if (message.content.extra && message.content.extra.data_type == 'price') { 	// 加价消息处理
                params.self.setData({
                    chart_topper: {
                        price: message.content.content,
                        nickname: message.content.extra.nickname || '恒基权品',
                        photo: message.content.extra.photo || src,
                        data_type: message.content.extra.data_type || 'price',
                        range: message.content.extra.range || 10
                    }
                })
                params.self.getNowGoodsData();
            }
        }
        if ( message.content.extra.data_type == "countDown" ) {
            messageList.push({
                messageType: 'countDown',
                content: message.content.content,
                messageUId: message.messageUId
            })
            if (message.content.content <= 1) {
                params.self.setData({
                    goods_status: false
                })
            }
        }
    }
    
    messageList = isRepeat(messageList, "messageUId")

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })
}

// 写入资料消息 
var writeInMaterial = function (num , message){
    var messageList = params.self.data.messageList;

    if (message.content.extra.data_type == "auctionStart"){
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId
        })

        params.self.getStatus();
    }
    if(message.content.extra.data_type == "auctionEnd") {
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId
        })

        params.self.getStatus();
    }

    if (message.content.extra.data_type == "start") {           // 如果是开始竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId:message.messageUId,
            content: {
                price_status: message.content.extra.price_status,
                index: message.content.extra.data.len,
                price: message.content.extra.data.price,
                goods_id: message.content.extra.data.goods_id,
                title: message.content.extra.data.title,
                nickname: message.content.extra.data.nicke_name,
            }
        })
        if (!params.self.data.aution_is_end) {
            params.self.getNowGoodsData();
        }
    }
    
    if (message.content.extra.data_type == "end") {              // 如果是结束竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                price_status: message.content.extra.price_status,
                index: message.content.extra.data.len,
                price: message.content.extra.data.price,
                goods_id: message.content.extra.data.goods_id,
                title: message.content.extra.title,
                nickname: message.content.extra.data.name,
            }
        })

        if (!params.self.data.aution_is_end) {
            params.self.getNowGoodsData();
        }
    }
    
    if (message.content.extra.data_type == "repeal") {              // 如果是撤销竞拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                price_status: message.content.extra.price_status,
                goods_id: message.content.extra.data.goods_id,
                title: message.content.extra.data.title,
            }
        })
        if (!params.self.data.aution_is_end) {
            params.self.getNowGoodsData();
        }
    }
    
    if (message.content.extra.data_type == "drain") {            // 如果是流拍
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                price_status: message.content.extra.price_status,
                index: message.content.extra.data.len,
                title: message.content.extra.data.title,
                goods_id: message.content.extra.data.goods_id,
            }
        })
        if (!params.self.data.aution_is_end) {
            params.self.getNowGoodsData();
        }
    }

    messageList = isRepeat(messageList, "messageUId")

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })
}

// 写入通知消息
var writeInNotification = function (num, message) {

    var messageList = params.self.data.messageList;
    if (message.content.extra.data_type == "shutup") {          // 如果是禁言通知
        messageList.push({
            messageType: message.content.extra.data_type,
            messageUId: message.messageUId,
            content: {
                value: message.content.extra.value
            }
        })
    }

    messageList = isRepeat(messageList, "messageUId")

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
        auction_shutup: message.content.extra.value
    })
}

// 写入后台发送的系统消息
var writeInAuctionStatus = function (num, message) {
    console.log("收到后台发送的消息")
    var messageList = params.self.data.messageList;

    if (message.content.message.content.data_type == "auctionStart") {            // 如果是开始活动
        messageList.push({
            messageType: message.content.message.content.data_type,
            messageUId: message.messageUId,
        })

        params.self.getStatus();
    }

    if (message.content.message.content.data_type == "auctionEnd") {              // 如果是活动结束
        messageList.push({
            messageType: message.content.message.content.data_type,
            messageUId: message.messageUId,
        })

        params.self.getStatus();
    }
    
    messageList = isRepeat(messageList,"messageUId")

    params.self.setData({
        toView: message.messageUId,
        messageList: messageList,
    })
}
/*  融云接收消息会出现重复 message  暂未找出解决方法，先作去重处理
 *  方法一：判断聊天消息是否有重复 如果这个方法不行 就只能用去重了... 
 *  arr :   数据列表
 *  key :   指定比对两条数据的 key 值
 */
function isAdjacent(arr,key){
    var len = arr.length;
    if (len < 2) {                                  // 是否只有一条数据
        return true;
    }
    if (arr[len - 1][key] == arr[len - 2][key]) {    // 判断当前这条消息 是否和上一条消息重复
        return false;
    }
    return true;
}


/*方法二 ：判断JSON数组是否有重复*/
function isRepeat(arr,key) {
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i][key]]){
            return distinctList(arr, key);
        } //hash 哈希
        hash[arr[i][key]] = true;
    }
    return arr;
}

/* 聊天消息去重
 *  array : 需要去重的数组
 *  key   : 指定 key 值 ， 根据该 key 值执行去重
 */
function distinctList(array, key) {
      var result = [array[0]];
      for (var i = 1; i < array.length; i++) {
            var item = array[i];
            var repeat = false;
            for (var j = 0; j < result.length; j++) {
                  if (item[key] == result[j][key]) {
                        repeat = true;
                        break;
                  }
            }
            if (!repeat) {
                  result.push(item);
            }
      }
      return result;
}


// 发送消息错误回调
var sendError = function (errorCode, message) {
    var info = '';
    switch (errorCode) {
        case RongIMLib.ErrorCode.TIMEOUT:
            info = '超时';
            break;
        case RongIMLib.ErrorCode.UNKNOWN:
            info = '未知错误';
            break;
        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
            info = '在黑名单中，无法向对方发送消息';
            break;
        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
            info = '不在讨论组中';
            break;
        case RongIMLib.ErrorCode.NOT_IN_GROUP:
            info = '不在群组中';
            break;
        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
            info = '不在聊天室中';
            joinChatRoom();
            break;
        default:
            info = x;
            break;
    }
    // console.log('发送失败:' + info);
    wx.showToast({
        image: '../../img/warning.png',
        title: '发送失败:' + info
    })
}